package cn.org.eshow.service.impl;

import cn.org.eshow.bean.query.CouponQuery;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.component.getui.GetuiUtil;
import cn.org.eshow.dao.CouponDao;
import cn.org.eshow.dao.UserDao;
import cn.org.eshow.model.Coupon;
import cn.org.eshow.model.Notification;
import cn.org.eshow.model.User;
import cn.org.eshow.model.UserCoupon;
import cn.org.eshow.service.CouponManager;
import cn.org.eshow.service.NotificationManager;
import cn.org.eshow.service.UserCouponManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.util.List;

@WebService(serviceName = "CouponService", endpointInterface = "cn.org.eshow.service.CouponManager")
@Service
public class CouponManagerImpl extends GenericManagerImpl<Coupon, Integer> implements CouponManager {

    @Autowired
    CouponDao couponDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserCouponManager userCouponManager;
    @Autowired
    NotificationManager notificationManager;

    public CouponManagerImpl() {
    }

    @Autowired
    public CouponManagerImpl(CouponDao couponDao) {
        super(couponDao);
        this.couponDao = couponDao;
    }

    @Override
    public List<Coupon> list(CouponQuery query) {
        return couponDao.list(query);
    }

    @Override
    public Page<Coupon> search(CouponQuery query) {
        return couponDao.search(query);
    }

    @Override
    public Coupon check(CouponQuery query) {
        List<Coupon> list = couponDao.list(query);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }
//
    @Override
    public long count(CouponQuery query) {
        return couponDao.count(query);
    }

    @Override
    public void distribution(Coupon coupon, String userIds) {
        coupon.setStock(coupon.getTotal());//库存等于总数
        coupon = couponDao.save(coupon);//保存优惠券信息
        String[] userIdArray = userIds.split(",");
        for (String userId : userIdArray) {
            User user = userDao.get(Integer.valueOf(userId));
            if (user != null) {
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setUser(user);
                userCoupon.setCoupon(coupon);
                userCoupon=userCouponManager.save(userCoupon);
                GetuiUtil.pushMessage(user.getClientId(),"消息通知","送优惠券啦，快来看看吧","userCoupon",userCoupon.getId().toString());
                notificationManager.save(user, Notification.Category.订单消息.toString(),"消息通知","送优惠券啦，快来看看吧","","userCoupon",userCoupon.getId().toString());

            }
        }
    }

}